package a66weding.com.jiehuntong.activity;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.makeramen.roundedimageview.RoundedImageView;
import java.util.ArrayList;
import java.util.List;
import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.home.BaseHomeActivity;
import a66weding.com.jiehuntong.adapter.CommonAdapter;
import a66weding.com.jiehuntong.adapter.ViewHolder;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.ThemeSettingsInfo;
import a66weding.com.jiehuntong.beans.ThemeStyles;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.CacheUtils;
import a66weding.com.jiehuntong.common.utils.Utils;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.view.ConfirmLoginDialog;
import a66weding.com.jiehuntong.wx.Util;
import static a66weding.com.jiehuntong.R.id.llay_nav_left;
import static a66weding.com.jiehuntong.activity.ThemeSettingsActivity.ACTION_REFRESH_PREVIEWINVITATION;
public class ElectronicInvitationHomeActivity extends BaseHomeActivity implements AdapterView.OnItemClickListener, View.OnClickListener, OnNetResultListener {
    private ArrayList<String> urls;
    private GridView mGV;
    private ImageView an_im;
    private ObjectAnimator animator4;
    private PopupWindow popupWindow;
    private GridView popGrideView;
    private List<ThemeStyles.DataBean> styleData;
    //头部导航条
    private RelativeLayout rlayNavContains;
    private LinearLayout llayNavLeft;
    private ImageView imgNavBack;
    private TextView tvNavLefttext;
    private LinearLayout llayNavRight;
    private TextView tvNavRightText;
    private TextView tvNavCenterText;
    private View viewBootomLine;
    private int currentThemeType;
    private SwipeRefreshLayout swipeRefresh;
    private LinearLayout electronicHomeRoot;
    private int useId;
    private RelativeLayout demonstrateRl;// 演示布局
    private ImageView demonstrateClassifyIv;// 主题类型布局
    private ImageView demonstrateMineIv;// 我的主题布局

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_electronic_invitation_home);
        //注册广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_REFRESH_PREVIEWINVITATION);
        registerReceiver(myReceiver, filter);
        initView();
        inintPOP();
        initeData();
    }

    //广播用来在预览设置后的更新
    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int previewID = intent.getIntExtra("previewID", -2);
            useId = previewID;
        }
    };

    private void initeData() {
        HttpRequestBean httpRequestBean = new HttpRequestBean();
        if (((GlobalApplication) this.getApplication()).isLogin()){
            int uId = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
            //当前设置请求
            httpRequestBean.setListener(this);
            httpRequestBean.setClazz(ThemeSettingsInfo.class);
            httpRequestBean.setRequestMethod(RequestCode.GETREQUEST);
            httpRequestBean.setUrl(RequestCode.SURL + RequestCode.CURRENTINVITESETTINGS + uId);
            HttpHandleUtil.executeCommonGet(this, httpRequestBean);
        }
        //模板风格
        httpRequestBean.setListener(this);
        httpRequestBean.setClazz(ThemeStyles.class);
        httpRequestBean.setRequestMethod(RequestCode.GETREQUEST);
        httpRequestBean.setUrl(RequestCode.SURL + RequestCode.THEMESTYLES);
        HttpHandleUtil.executeCommonGet(this, httpRequestBean);
    }

    private void inintPOP() {
        View view = this.getLayoutInflater().inflate(R.layout.pop_theme_style, null);
        view.findViewById(R.id.pop_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    viewBootomLine.setBackgroundColor(getResources().getColor(R.color.colortheme));
                }
            }
        });
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        popGrideView = (GridView) view.findViewById(R.id.pop_gv_styles);
        popGrideView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListAdapter adapter = popGrideView.getAdapter();
                ThemeStyles.DataBean typeItem = (ThemeStyles.DataBean) adapter.getItem(position);
                currentThemeType = typeItem.getI_id();
                setImagesAdaputer(currentThemeType);//设置当前需要显示的图画廊
                tvNavRightText.setText(typeItem.getNvc_Name());
                //修改按钮颜色
                if (adapter != null && popGrideView.getCount() > 0) {
                    for (int i = 0; i < adapter.getCount(); i++) {
                        LinearLayout item = (LinearLayout) popGrideView.getChildAt(i);
                        TextView childAt = (TextView) item.getChildAt(0);
                        if (position == i) {
                            childAt.setSelected(true);
                        } else {
                            childAt.setSelected(false);
                        }
                    }
                }
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    viewBootomLine.setBackgroundColor(getResources().getColor(R.color.colortheme));
                }
            }
        });
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.color.push_translucent);
        BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
        popupWindow.setBackgroundDrawable(bitmapDrawable);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.setContentView(view);
    }

    private void initView() {
        electronicHomeRoot = (LinearLayout) findViewById(R.id.ll_electronic_home_root);
        //头部导航条
        rlayNavContains = (RelativeLayout) findViewById(R.id.rlay_nav_contains);
        llayNavLeft = (LinearLayout) findViewById(llay_nav_left);
        imgNavBack = (ImageView) findViewById(R.id.img_nav_back);
        tvNavLefttext = (TextView) findViewById(R.id.tv_nav_lefttext);
        llayNavRight = (LinearLayout) findViewById(R.id.llay_nav_right);
        tvNavRightText = (TextView) findViewById(R.id.tv_nav_righttext);
        tvNavCenterText = (TextView) findViewById(R.id.tv_nav_center_text);
        viewBootomLine = (View) findViewById(R.id.view_bootom_line);
        viewBootomLine.setBackgroundColor(getResources().getColor(R.color.color_nav_theme));
        rlayNavContains.setBackgroundColor(getResources().getColor(R.color.colortheme));
        tvNavCenterText.setText("主题浏览");
        tvNavRightText.setText("");
        tvNavLefttext.setText("返回");
        llayNavLeft.setOnClickListener(this);
        llayNavRight.setOnClickListener(this);

        mGV = (GridView) findViewById(R.id.grid_view);
        an_im = (RoundedImageView) findViewById(R.id.an_im);
        mGV.setOnItemClickListener(this);
        swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        swipeRefresh.setRefreshing(true);
        swipeRefresh.setColorSchemeResources(R.color.colorMainRed);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initeData();
            }
        });

        demonstrateRl = (RelativeLayout) findViewById(R.id.demonstrate_rl);
        demonstrateClassifyIv = (ImageView) findViewById(R.id.demonstrate_classify_iv);
        demonstrateMineIv = (ImageView) findViewById(R.id.demonstrate_mine_iv);
        boolean isDemonstrated = CacheUtils.getBooleanFromCache(ElectronicInvitationHomeActivity.this, "isDemonstrated");
        if (!isDemonstrated) {
            demonstrateRl.setVisibility(View.VISIBLE);
            demonstrateClassifyIv.setVisibility(View.VISIBLE);
            demonstrateMineIv.setVisibility(View.GONE);
        } else {
            demonstrateRl.setVisibility(View.GONE);
        }
        demonstrateRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (demonstrateMineIv.getVisibility() == View.GONE) {
                    demonstrateMineIv.setVisibility(View.VISIBLE);
                    demonstrateClassifyIv.setVisibility(View.GONE);
                } else {
                    demonstrateRl.setVisibility(View.GONE);
                    CacheUtils.setBooleanToCache(ElectronicInvitationHomeActivity.this, "isDemonstrated", true);
                }
            }
        });
    }

    public void myElectronicInvitation(View view) {
        if (((GlobalApplication) this.getApplication()).isLogin()) {
            Intent intent = new Intent(ElectronicInvitationHomeActivity.this, ElectronicInvitationActivity.class);
            startActivity(intent);
        }else {
            showLoginDialog(this, "亲，需要登录哦~", "去登录", "取消");
        }
    }
    public  void showLoginDialog(final Context context, String title, String confirm, String cancel) {
        final ConfirmLoginDialog confirmDialog = new ConfirmLoginDialog(context, title, confirm, cancel,R.layout.pop_tologin);
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmLoginDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                Intent intent = new Intent(ElectronicInvitationHomeActivity.this, LoginActivity.class);
                ElectronicInvitationHomeActivity.this.startActivityForResult(intent,666);
                confirmDialog.dismiss();
            }
            @Override
            public void doCancel() {
                confirmDialog.dismiss();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==666&&resultCode==200){
            //当前设置请求
            HttpRequestBean httpRequestBean = new HttpRequestBean();
            if (((GlobalApplication) this.getApplication()).isLogin()){
                int uId = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
                //当前设置请求
                httpRequestBean.setListener(this);
                httpRequestBean.setClazz(ThemeSettingsInfo.class);
                httpRequestBean.setRequestMethod(RequestCode.GETREQUEST);
                httpRequestBean.setUrl(RequestCode.SURL + RequestCode.CURRENTINVITESETTINGS + uId);
                HttpHandleUtil.executeCommonGet(this, httpRequestBean);
            }
            Intent intent = new Intent(ElectronicInvitationHomeActivity.this, ElectronicInvitationActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        //view.setVisibility(View.INVISIBLE);//隐藏当前的item(目前说不需要暂时留着)
        LinearLayout lvs = (LinearLayout) view;
        RoundedImageView childAt = (RoundedImageView) lvs.getChildAt(0);
        Drawable drawable = childAt.getDrawable();
        an_im.setVisibility(View.VISIBLE);
        ViewGroup.LayoutParams layoutParams = an_im.getLayoutParams();
        layoutParams.height = view.getHeight();
        layoutParams.width = view.getWidth();
        an_im.setLayoutParams(layoutParams);
        an_im.setImageDrawable(drawable);
        float x = view.getX();
        float y = view.getY();
        //移动到父控件正中
      /*  ObjectAnimator animator3 = ObjectAnimator.ofFloat(an_im, "translationX", x, (mGV.getWidth() - view.getWidth()) / 2);
        animator4 = ObjectAnimator.ofFloat(an_im, "translationY", y + getResources().getDimension(R.dimen.bigfont52), (mGV.getHeight() - view.getHeight()) / 2 + ((float) getResources().getDimension(R.dimen.bigfont52)) / 3 * 2);*/
        //缩放//缩放到父控件大小
/*        ObjectAnimator animator = ObjectAnimator.ofFloat(an_im, "scaleX", 1.0f, (float) mGV.getWidth() / view.getWidth());
        ObjectAnimator animator1 = ObjectAnimator.ofFloat(an_im, "scaleY", 1.0f, (float) (mGV.getHeight() + getResources().getDimension(R.dimen.bigfont52)) / view.getHeight());*/

        ObjectAnimator animator3 = ObjectAnimator.ofFloat(an_im, "translationX", x, (Utils.getScreenWidth(this) - view.getWidth()) / 2);
        animator4 = ObjectAnimator.ofFloat(an_im, "translationY", y + getResources().getDimension(R.dimen.bigfont52) + rlayNavContains.getHeight(), (electronicHomeRoot.getHeight() - view.getHeight()) / 2);

        ObjectAnimator animator = ObjectAnimator.ofFloat(an_im, "scaleX", 1.0f, (float) Utils.getScreenWidth(this) / view.getWidth());
        ObjectAnimator animator1 = ObjectAnimator.ofFloat(an_im, "scaleY", 1.0f, (float) electronicHomeRoot.getHeight() / view.getHeight());

        AnimatorSet set = new AnimatorSet();
        set.play(animator3).with(animator4).before(animator).before(animator1);
        set.setDuration(200);
        set.start();
        set.addListener(new Animator.AnimatorListener() {

            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                //动画执行完成后进行跳转到预览
                Intent intent = new Intent(ElectronicInvitationHomeActivity.this, PreviewThemeActivity.class);
                ThemeStyles.DataBean.TemplateListBean itemData = (ThemeStyles.DataBean.TemplateListBean) mGV.getAdapter().getItem(position);
                intent.putExtra("TempUrl", itemData.getTempUrl());
                intent.putExtra("tid", itemData.getI_id());
                intent.putExtra("useId", useId);
                startActivity(intent);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
    }

    @Override
    protected void onResume() {
        //再次执行一个动画还原
        ObjectAnimator animator4 = ObjectAnimator.ofFloat(an_im, "scaleX", 1.0f).setDuration(1);
        ObjectAnimator animator5 = ObjectAnimator.ofFloat(an_im, "scaleY", 1.0f).setDuration(1);
        animator4.start();
        animator5.start();
        an_im.setVisibility(View.GONE);
        super.onResume();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llay_nav_left:
                finish();
                break;
            case R.id.llay_nav_right:
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else if (popupWindow != null && !popupWindow.isShowing()) {
                    popupWindow.showAsDropDown(viewBootomLine, Gravity.BOTTOM, Gravity.CENTER_HORIZONTAL);//设置在屏幕中的显示位置
                }
                break;
        }
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();

        if (data instanceof ThemeStyles) {
            if(swipeRefresh != null){
                swipeRefresh.setRefreshing(false);
            }
            ThemeStyles themeStyles = (ThemeStyles) data;
            if (themeStyles != null && themeStyles.getResCode() != null) {
                if (themeStyles.getResCode().equals("0000")) {
                    //所有需要使用到数据
                    styleData = themeStyles.getData();
                    setDate2popGride();
                    if (styleData.size() > 0 && styleData != null) {
                        currentThemeType = styleData.get(0).getI_id();
                        tvNavRightText.setText(styleData.get(0).getNvc_Name());
                    }
                    setImagesAdaputer(currentThemeType);
                } else if (data instanceof ThemeSettingsInfo) {//页面当前使用的设置
                    ThemeSettingsInfo response = (ThemeSettingsInfo) data;
                    if (response != null && response.getResCode() != null) {
                        if (response.getResCode().equals("0000")) {
                            //用户使用的
                            useId = response.getData().getI_Tid();
                        } else {
                            CUtils.showToast(response.getMsg());
                        }
                    }
                } else {
                    CUtils.showToast(themeStyles.getMsg());
                }
            }
        }
    }

    @Override
    public void onError(ErrorBean errorBean) {

    }

    private void setImagesAdaputer(int type) {//设置显示的图片根据风格类型
        for (ThemeStyles.DataBean tll : styleData) {
            if (tll.getI_id() == type) {
                final List<ThemeStyles.DataBean.TemplateListBean> templateList = tll.getTemplateList();
                if (templateList.size() > 0) {
                    CommonAdapter<ThemeStyles.DataBean.TemplateListBean> commonAdapter = new CommonAdapter<ThemeStyles.DataBean.TemplateListBean>(this, templateList, R.layout.item_invitation_home) {
                        @Override
                        public void convert(ViewHolder holder, ThemeStyles.DataBean.TemplateListBean templateListBean) {
                            final RoundedImageView img = (RoundedImageView) holder.getView(R.id.img_invitation_home);
                            /*android:layout_width="@dimen/bigsize464"
                            android:layout_height="@dimen/bigsize736"
                    android:horizontalSpacing="@dimen/bigsize42"
                    android:paddingLeft="@dimen/bigsize50"
                    android:paddingRight="@dimen/bigsize50"
                    android:verticalSpacing="@dimen/bigsize56"></GridView>
                            */
                            //这里一定要加上asBitmap因为不加的话,RoundedImageView内存中第一次有该图片后无法圆角
                            int screenWidth = Utils.getScreenWidth(ElectronicInvitationHomeActivity.this);
                            Glide.with(ElectronicInvitationHomeActivity.this).load(templateListBean.getNvc_Thumbnail()).asBitmap().placeholder(R.mipmap.bg_loadimage).into(img);
                            float scle=((screenWidth-50*2-56)/2.0f)/464;
                            Log.i("img", "convert: scle"+scle);
                            ViewGroup.LayoutParams params = img.getLayoutParams();
                            params.width = (int) ((screenWidth-50*2-56)/2.0f);
                            params.height = (int) (736*scle);
                            img.setLayoutParams(params);
                        }
                    };
                    mGV.setAdapter(commonAdapter);
                }
                break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        //取消注册的广播
        unregisterReceiver(myReceiver);
        if (urls != null) {
            for (String s : urls) {
                s = null;
            }
            urls = null;
        }
        mGV = null;
        Util.releaseImageView(an_im);
        animator4 = null;
        popupWindow = null;
        popGrideView=null;
        if (null!=styleData){
            for (ThemeStyles.DataBean s:styleData){
                s=null;
            }
            styleData=null;
        }
        llayNavLeft=null;
        Util.releaseImageView( imgNavBack);
        tvNavLefttext=null;
        llayNavRight=null;
        tvNavRightText=null;
        tvNavCenterText=null;
        viewBootomLine=null;
        swipeRefresh=null;
        electronicHomeRoot=null;
        demonstrateRl=null;;// 演示布局
        Util.releaseImageView(demonstrateMineIv);
        Util.releaseImageView(demonstrateClassifyIv);
        super.onDestroy();
    }

    private void setDate2popGride() {
        CommonAdapter<ThemeStyles.DataBean> commonAdapter = new CommonAdapter<ThemeStyles.DataBean>(this, styleData, R.layout.itme_styles) {
            @Override
            public void convert(ViewHolder holder, ThemeStyles.DataBean dataBean) {
                int i_id = dataBean.getI_id();
                TextView btnStyle = holder.getView(R.id.btn_style);
                btnStyle.setText(dataBean.getNvc_Name());
                if (currentThemeType == i_id) {
                    btnStyle.setSelected(true);
                }
            }
        };
        popGrideView.setAdapter(commonAdapter);
    }
}

